package com.pig.jjfetion.core.utils;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;

import org.apache.log4j.Logger;
import org.jdom.Document;
import org.jdom.Element;
import org.jdom.JDOMException;
import org.jdom.input.SAXBuilder;

import com.pig.jjfetion.core.exception.ParseException;


public class XMLHelper {

	private static Logger logger = Logger.getLogger(XMLHelper.class);
	
	/**
	 * 从流中构建dom对象
	 * @return 构造成功返回根元素
	 * @throws ParseException
	 */
	public static Element build(InputStream in) throws ParseException{
		try {
			SAXBuilder builder = new SAXBuilder();
			Document doc = builder.build(in);
			return doc.getRootElement();
			
		} catch (JDOMException e) {
			logger.warn("Cannot parse XML Stream:"+e);
			throw new ParseException(e);
		} catch (IOException e) {
			logger.warn("IOException occured when parse XML Stream:"+e);
			throw new ParseException(e);
		}
	}
	/*
	 * 从字符串中构建dom对象
	 * @param xml
	 * @return
	 * @throws ParseException
	 */
	public static Element builder(String xml) throws ParseException{
		
		try {
			return build(new ByteArrayInputStream(xml.getBytes("utf8")));
		} catch (UnsupportedEncodingException e) {
			logger.error("error occured when parse dom from string:"+e);
			throw new ParseException(e);
		}
	}
	/*
	 * 以给定的路径查找列表元素
	 * contacts/*contact 表示查找contacts下面的所有的名字为contact的节点
	 * /results/contacts/*contact 和上面一样的结果 如果以/开始表示从根节点查询起
	 * @param tree
	 * @param path
	 * @return
	 */
	public static List findAll(Element tree, String path){
		
		if(tree == null || path == null){
			return new ArrayList();
		}
		if(path.charAt(0)=='/'){
			path = path.substring(path.indexOf('/', 1)+1);
		}
		String[] paths = path.split("/");
		for(int i=0; i<path.length(); i++){
			tree = tree.getChild(paths[i]);
			if(tree == null) return new ArrayList();
		}
		List els = null;
		String last = paths[paths.length-1];
		if(last.length()>=1 && last.charAt(0)=='*'){
			els = tree.getChildren();
		}else{
		    els = tree.getChildren(last.substring(1));
		}
		return els;
	}
	
	/**
	 * 以给定的路径查找特定的元素
	 *   contact/basic 表示查找contact下面子节点名字为basic的节点
	 *   /results/contact/basic 和上面一样的结果 如果以/开始表示从根节点查询起
	 * @param tree		
	 * @param path
	 * @return
	 */
	public static Element find(Element tree, String path)
	{
		if(tree==null || path==null)	
			return null;
		if(path.charAt(0)=='/')
			path = path.substring( path.indexOf('/', 1)+1);
		String[] paths = path.split("/");
		for(int i=0; i<paths.length; i++) {
			tree = tree.getChild(paths[i]);
			if(tree==null)
				return null;
		}
		return tree;
	}
	
	
}
